package com.sisucc.contractmanage.serviceImpl.loginServiceImpl;

import com.sisucc.contractmanage.bean.accountInfo.AccountInfoBean;
import com.sisucc.contractmanage.dao.accountInfo.AccountInfoRepository;
import com.sisucc.contractmanage.service.loginService.UserDetailsServiceNative;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * @author linyuqi
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsServiceNative, UserDetailsService {

    @Autowired
    private AccountInfoRepository accountInfoRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        String password = "";
        AccountInfoBean accountInfoBean = accountInfoRepository.findByAccountCode(username);
        if (Optional.ofNullable(accountInfoBean).isPresent()) {
            if (accountInfoBean.getAccountCode().equals(username)) {
                password = accountInfoBean.getAccountPassword();
            }
        }

        return new User(username, password, AuthorityUtils.commaSeparatedStringToAuthorityList("root"));
    }
}
